package cn.topevery.garden.dal.util;

import hw.topevery.basis.dal.logic.SysDeptLogic;
import hw.topevery.basis.dal.logic.SysUserInDeptLogic;
import hw.topevery.basis.entity.dto.DeptDto;
import hw.topevery.basis.entity.fetch.DeptFetch;
import hw.topevery.basis.entity.po.SysDept;
import hw.topevery.basis.entity.po.SysUser;
import hw.topevery.framework.db.entity.DataPager;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class DeptUtil {

    @Autowired
    private SysDeptLogic deptLogic;

    @Autowired
    private SysUserInDeptLogic sysUserInDeptLogic;

    public List<String> setAuthDeptList(SysUser user) {
        List<DeptDto> authDeptList = getAuthDeptList(user);
        if (CollectionUtils.isEmpty(authDeptList)) {
            return null;
        }
        return authDeptList.stream().map(dept -> dept.deptId).collect(Collectors.toList());
    }

    public List<DeptDto> getAuthDeptList(SysUser user) {
        if (user.userIsAdmin != 1) {
            List<SysDept> userInDeptList = sysUserInDeptLogic.getListDept(user.userId);
            if (CollectionUtils.isEmpty(userInDeptList)) {
                return null;
            }
            List<DeptDto> authDeptList = new ArrayList<>();
            userInDeptList.forEach(userInDept -> {
                DeptFetch deptFetch = new DeptFetch();
                deptFetch.setDeptId(userInDept.deptId);
                deptFetch.setPageIndex(1);
                deptFetch.setPageSize(100);
                DataPager<DeptDto> list = deptLogic.getList(deptFetch);
                authDeptList.addAll(list.records);
            });
            return authDeptList;
        }
        return null;
    }
}
